import TIM from 'tim-js-sdk';
import COS from 'cos-js-sdk-v5';
import { getuserinfo } from '../redux/actionCreator';
import TRTCCalling from 'trtc-calling-js';

let options = {
    SDKAppID: 1400458473
};
let tim = TIM.create(options);
const trtcCalling = new TRTCCalling(options);
trtcCalling.setLogLevel(1);
tim.setLogLevel(1);
tim.registerPlugin({ 'cos-js-sdk': COS });

tim.on(TIM.EVENT.SDK_READY, function () {
    localStorage.setItem('sdkready', true)
    console.log('我准备好了！！！')
})
const Login_tim = (userid, user_sig) => {
    let promise = tim.login({ userID: userid, userSig: user_sig });
    promise.then(function (imResponse) {
        console.log('登陆:' + userid)
        if (imResponse.data.repeatLogin === true) {
            // 标识账号已登录，本次登录操作为重复登录。v2.5.1 起支持
            console.log('重复登陆')
        }
    }).catch(function (imError) {
        console.warn('login error:', imError); // 登录失败的相关信息
    });
}

// tim.on(TIM.EVENT.MESSAGE_RECEIVED, function (event) {
//    console.log(event.data)

// });

const Add_msg_tim = (event) => {
    return (dispatch) => {
        dispatch({
            type: 'ADD_MSG',
            value: event.data[0]
        })
    }
}
// 得到会话内容并放入reducer
const Msgget_tim = (phone) => {
    return (dispatch) => {
        // tim.on(TIM.EVENT.SDK_READY, function getmsgcon(event) {
        // 收到离线消息和会话列表同步完毕通知，接入侧可以调用 sendMessage 等需要鉴权的接口
        // console.log(event)
        let promise = tim.getMessageList({ conversationID: `C2C${phone}`, count: 15 });
        promise.then((imResponse) => {
            const list = imResponse.data.messageList
            console.log(list)
            dispatch({
                type: 'GET_MSG',
                value: list
            })
        });
    }
}
// 发消息
const Send_tim = (phone, text) => {
    return (dispatch) => {
        let message = tim.createTextMessage({
            to: `${phone}`,
            conversationType: TIM.TYPES.CONV_C2C,
            payload: {
                text: `${text}`
            }
        });
        let promise = tim.sendMessage(message);
        promise.then(function (imResponse) {
            // 发送成功
            dispatch({
                type: 'ADD_MSG',
                value: imResponse.data.message
            })
        }).catch(function (imError) {
            // 发送失败
            console.warn('sendMessage error:', imError);
        });
    }
}
// 获取会话列表
const Conget_tim = (props) => {
    return (dispatch) => {
        let promise = tim.getConversationList();
        promise.then(function (imResponse) {
            const conversationList = imResponse.data.conversationList; // 会话列表，用该列表覆盖原有的会话列表
            dispatch({
                type: 'GET_CON',
                value: conversationList
            })
            console.log(1)
            if (props) {
                for (let i = 0; i < conversationList.length; i++) {

                    props.dispatch(getuserinfo(conversationList[i].conversationID.replace('C2C', ''), props))
                }
            }
        }).catch(function (imError) {
            console.warn('getConversationList error:', imError); // 获取会话列表失败的相关信息
        });
    }
}
// 会话列表更新
const Conadd_tim = (event) => {
    return (dispatch) => {
        dispatch({
            type: 'GET_CON',
            value: event.data
        })
    }
}
// 清空message中信息用于C2C C2C2 goback处 
const Msgdel_tim = () => {
    return (dispatch) => {
        dispatch({
            type: 'DEL_MSG'
        })
    }
}

// 退出登录
const Loginout_tim = () => {
    let promise = tim.logout();
    promise.then(function (imResponse) {
        console.log('登出成功' + imResponse.data); // 登出成功
    }).catch(function (imError) {
        console.warn('logout error:', imError);
    });
}


// 音视频通话通用的登录
// 在im登录处一起登录算求
const VAudio_login = (userid, user_sig) => {
    let promise = trtcCalling.login({ userID: userid, userSig: user_sig });
    promise.then(() => {
        //success
        console.log('电话登录')
    }).catch(error => {
        console.warn('login error:', error)
    });
}
// ready之后可以发起音频
// 音视频其实只是1与2的区别写一个函数足以
// 发起通话请求
const VAudio_call = (phone, type) => {
    let promise = trtcCalling.call({ userID: phone, type: type, timeout: 0 });
    promise.then(() => {
        console.log('通话邀请成功')
    }).catch(error => {
        console.warn('call error:', error)
    });
}
// 接受视频邀请
const VAudio_invit = (event, type) => {
    trtcCalling.accept({
        inviteID: event.inviteID,
        roomID: event.inviteData.roomID,
        callType: type
    });
}
// 拒绝通话邀请
const VAudio_reject = (event, type) => {
    trtcCalling.reject({
        inviteID: event.inviteID,
        roomID: event.inviteData.roomID,
        callType: type
    });
}
// 退出登录
const VAudio_loginout = () => {
    let promise = trtcCalling.logout();
    promise.then(() => {
        //success
    }).catch(error => {
        console.warn('logout error:', error)
    });
}
// 挂电话
const VAudio_hangup = () => {
    trtcCalling.hangup();
}
// 音频童话
// 视频通话
// 视频通话中的渲染网络画面对方的样子
const Video_canvs = (phone) => {
    let promise = trtcCalling.startRemoteView({ userID: phone, videoViewDomID: 'video_she' });
    promise.then(() => {
        //success
    }).catch(error => {
        console.warn('startRemoteView error:', error)
    });
}
// 停止渲染关闭摄像头
const Video_stop = (phone) => {
    trtcCalling.stopRemoteView({ userID: phone, videoViewDomID: 'video_she' });
}
const Video_canvs_location = (phone) => {
    let promise = trtcCalling.startLocalView({ userID: phone, videoViewDomID: 'video_he' });
    promise.then(() => {
        //success
    }).catch(error => {
        console.warn('startLocalView error:', error)
    });
}
const Video_stop_location = (phone) => {
    trtcCalling.stopLocalView({ userID: phone, videoViewDomID: 'video_he' });
}
// 是否开启麦克风
const Audio = (type) => {
    trtcCalling.setMicMute(type)
}
// 开启摄像头
const Video_open = () => {
    trtcCalling.openCamera();
}
// 关闭摄像头
const Video_close = () => {
    trtcCalling.closeCamera();
}
export {
    Login_tim, Msgget_tim, Send_tim, Conget_tim, Add_msg_tim, Msgdel_tim, Conadd_tim, Loginout_tim,
    VAudio_login, VAudio_call, Video_canvs, VAudio_invit, VAudio_loginout, VAudio_reject, VAudio_hangup, Video_stop, Video_canvs_location, Video_stop_location, Audio, Video_open, Video_close
}
// VAudio_call 基于事件 TIM.EVENT.SDK_READY
// Video_canvs 基于事件 TRTCCalling.EVENT.USER_ENTER
// Video_canvs_location
// VAudio_invit 基于事件 TRTCCalling.EVENT.INVITED 收到邀请事件
// VAudio_reject 基于事件TRTCCalling.EVENT.INVITED